// 导入React核心功能
import React, { useState, useRef, useEffect } from 'react'
// 导入Ant Design Pro组件类型
import type { ActionType, ProColumns } from '@ant-design/pro-components'
// 导入Ant Design Pro表格组件
import { ProTable } from '@ant-design/pro-components'
// 导入Ant Design基础组件
import { Button, Space, Tag } from 'antd'
// 导入Ant Design应用容器
import { App } from 'antd'
// 导入删除考试API
import { deleteExamApi } from '@/service/exam'
// 导入考试项类型定义
import type { ExaminationItem, UserListItem } from '@/service/type'

import { getUserListApi } from '@/service/index'

/**
 * 定义组件props接口
 * data - 考试数据数组
 * loading - 加载状态
 * pagination - 分页配置
 *   current - 当前页码
 *   pageSize - 每页条数
 *   total - 总条数
 * onPageChange - 分页变化回调
 * onViewDetail - 查看详情回调
 */
interface ExamHistoryTableProps {
  data: ExaminationItem[]
  loading: boolean
  pagination: {
    current: number
    pageSize: number
    total: number
  }
  onPageChange: (page: number, pageSize: number) => void
  onViewDetail: (examId: string) => void
}

// 考试历史表格组件
const ExamHistoryTable: React.FC<ExamHistoryTableProps> = ({
  data,
  pagination,
  onPageChange,
  onViewDetail
}) => {
  // 加载状态
  const [loading, setLoading] = useState(false)
  // 用户列表
  const [userList, setUserList] = useState<UserListItem[]>([])


  // 获取Ant Design的modal和message实例
  const { modal, message } = App.useApp()

  // 格式化日期时间
  const formatDateTime = (isoStr: string): string => {
    const date = new Date(isoStr);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    const milliseconds = String(date.getMilliseconds()).padStart(3, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}.${milliseconds}`;
  }

  // 获取创建人名称  id: string
  const getUserList = async () => {
    try {
      setLoading(true);
      const userListRes = await getUserListApi();
      if (userListRes.data.data.list) {
        setUserList(userListRes.data.data.list);
      }
    } catch (error) {
      console.error('获取用户列表失败:', error);
      message.error('获取用户列表失败');
    } finally {
      setLoading(false);
    }
  }

  const getCreatorName = (id?: string) => {
    if (!id || !userList || userList.length === 0) return '未知用户';
    
    const userIndex = userList.findIndex(user => user._id === id);
    if (userIndex === -1) return '未知用户';
    
    const user = userList[userIndex];
    return user?.username || '未知用户';
  }



  useEffect(()=> {
    getUserList()
  },[])

  /**
   * 处理删除考试
   * @param examId 考试ID
   */
  const handleDelete = async (examId: string) => {
    modal.confirm({
      title: '确认删除',
      content: '确定要删除这条考试记录吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          setLoading(true)
          await deleteExamApi(examId) // 调用删除API，传入数组参数
          onPageChange(pagination.current, pagination.pageSize) // 刷新数据
          message.success('删除成功')
        } catch (error) {
          message.error('删除失败')
        } finally {
          setLoading(false)
        }
      }
    })
  }

  /**
   * 搜索参数接口
   * name - 考试名称
   * classify - 科目分类
   * creator - 创建人
   * status - 考试状态
   */
  interface SearchParams {
    name?: string
    classify?: string
    creator?: string
    status?: number
    createdAt?: string
  }

  // 搜索参数状态
  const [searchParams, setSearchParams] = useState<SearchParams>({})
  // 表格操作引用
  const actionRef = useRef<ActionType>(null)

  const columns: ProColumns<ExaminationItem>[] = [
    {
      title: '考试名称',
      dataIndex: 'name',
      key: 'name',
      search: {
        transform: (value) => {
          setSearchParams((prevParams) => ({ ...prevParams, name: value }))
          return { name: value }
        },
      },
    },
    {
      title: '科目分类',
      dataIndex: 'classify',
      key: 'classify',
      render: (_, record) => <>{record.classify ? record.classify?.name : '未设置'}</>,
      search: {
        transform: (value) => {
          setSearchParams((prevParams) => ({ ...prevParams, classify: value }))
          return { classify: value }
        },
      }
    },
    {
      title: '创建人',
      dataIndex: 'creator',
      key: 'creator',
      render: (_, record) => <>{(getCreatorName(record?.creator)) || '未设置'}</>,
      search: {
        transform: (value) => {
          setSearchParams((prevParams) => ({ ...prevParams, creator: value }))
          return { creator: value }
        },
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (_, record) => <>{record.createdAt ? formatDateTime(record.createdAt) : '未设置'}</>
    },
    {
      title: '开始时间',
      dataIndex: 'startTime',
      key: 'startTime',
      render: (_, record) => record.startTime ? new Date(record.startTime).toLocaleString() : '未设置',
    },
    {
      title: '结束时间',
      dataIndex: 'endTime',
      key: 'endTime',
      render: (_, record) => record.endTime ? new Date(record.endTime).toLocaleString() : '未设置',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      search: {
        transform: (value) => {
          setSearchParams((prevParams) => ({ ...prevParams, status: Number(value) }))
          return { status: Number(value) }
        },
      },
      valueEnum: {
        0: { text: '未开始', status: 'Default' },
        1: { text: '已结束', status: 'Processing' },
        2: { text: '进行中', status: 'Error' },
      },
      render: (_, record) => (
        <Tag color={record.status === 2 ? 'green' : 'red'}>
          {record.status === 2 ? '进行中' : '已结束'}
        </Tag>
      ),
    },
    {
      title: '监考人',
      dataIndex: 'examiner',
      key: 'examiner',
      render: (_, record) => {
        if (!record.examiners[0]) return '未设置'
        return <>
          {record.examiners?.map((examiner: any) => (
            <Tag key={examiner._id}>
              {examiner.username}
            </Tag>
          ))}
        </>
      }
    },
    {
      title: '考试班级',
      dataIndex: 'group',
      key: 'group',
      render: (_, record) => {
        if (!record.groups[0]) return '未设置'
        return <>
          {record.groups?.map((group) => (
            <Tag color="geekblue" key={group._id}>
              {group.name}
            </Tag>
          ))}
        </>
      },
    },
    {
      title: '修改时间',
      dataIndex: 'updatedAt',
      key: 'updatedAt',
      render: (_, record) => <>{record.updatedAt ? formatDateTime(record.updatedAt) : '未设置'}</>
    },
    {
      title: '设置',
      key: 'settings',
      width: 180,
      render: (_, record) => (
        <Space size="middle">
          <Button
            key="preview"
            type="link"
            onClick={() => onViewDetail(record._id)}
          >
            预览试卷
          </Button>
          <Button
            key="delete"
            type="link"
            danger
            onClick={() => handleDelete(record._id)}
            loading={loading}
          >
            删除
          </Button>
        </Space>
      ),
    },
    {
      title: '操作',
      key: 'operations',
      render: () => (
        <Button type="link" color="primary" variant="filled">成绩分析</Button>
      ),
    },
  ]

  // 根据搜索参数过滤数据
  const filteredData = data.filter((item) => {
    const { name, classify, creator, status } = searchParams
    if (name && item.name && !item.name.includes(name)) return false
    if (classify && item.classify && !item.classify.name.includes(classify)) return false
    if (creator && item.creator && !item.creator.includes(creator)) return false
    if (status !== undefined && item.status !== undefined && item.status !== status) return false
    return true
  })

  // 更新 pagination.total
  const updatedPagination = {
    ...pagination,
    total: filteredData.length
  }

  return (
    <ProTable<ExaminationItem>
      scroll={{ x: 1300, y: 500 }}
      columns={columns}
      dataSource={filteredData}
      actionRef={actionRef}
      loading={loading}
      rowKey="_id"
      search={{
        labelWidth: 'auto',
      }}
      pagination={{
        ...updatedPagination,
        showSizeChanger: true,
        showTotal: (total) => `共 ${total} 条考试记录`,
        onChange: (page, pageSize) => onPageChange(page, pageSize),
      }}
    />
  )
}

export default ExamHistoryTable